package cn.itcast.bos.service.base.impl;

import java.util.Date;
import java.util.Set;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.constant.Constant;
import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.dao.base.FixedAreaRepository;
import cn.itcast.bos.dao.base.OrderRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.base.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderRepository orderRepository;
	
	@Autowired
	private AreaRepository areaRepository;
	
	@Autowired
	private  FixedAreaRepository fixedAreaRepository;
	
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmstemplate;
	
	
	@Override
	public void saveOrder(Order order) {
		//设置订单号
		order.setOrderNum(UUID.randomUUID().toString());
		//下单时间
		order.setOrderTime(new Date());
		//订单状态(1 待取件 2 运输中 3 已签收 4 异常)
		order.setStatus("1");
		
		//将送货区域对象与收货区域变为持久对象并保存到order中
		Area sendArea = order.getSendArea();
		Area area1 = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(),sendArea.getCity(),sendArea.getDistrict());
		order.setSendArea(area1);
		
		Area recArea = order.getRecArea();
		Area area2 = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(),recArea.getCity(),recArea.getDistrict());
		order.setRecArea(area2);
		
		//自动分单:根据客户输入的准确发货地址,调用crm后台管理系统service,查询定区编号
		String fixedAreaId = WebClient.create(Constant.CRM_MANAGEMENT_URL+"/services/customerService/customer/findFixedAreaId/"+
				order.getSendAddress()).accept(MediaType.APPLICATION_JSON).get(String.class);
		System.out.println("fixedAreaId="+fixedAreaId);
		//根据定区id查询所有的快递员
		if(null!=fixedAreaId){	
			FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
			Set<Courier> couriers = fixedArea.getCouriers();
			if(null!=couriers){
				Courier courier = couriers.iterator().next();
				if(null!=courier){
					System.out.println("自动分单成功");
					System.out.println("快递员姓名为:"+courier.getName());
					
					//保存订单
					savOrder(order,courier);
					//生成工单
					generateWorkBill(order);
					return;
				}
			}
			
		}	
		
		//自动分单,根据关键分区关键字查询分区-----定区----快递员 
		for(SubArea subArea: order.getSendArea().getSubareas()){
			//判断用户输入的发货地址是否包含分区的关键字
			if(order.getSendAddress().contains(subArea.getKeyWords())){
				//如果包含,根据分区找到定区
				FixedArea fixedArea = subArea.getFixedArea();
				if(fixedArea!=null){
					Set<Courier> couriers = fixedArea.getCouriers();
					if(couriers!=null){
						Courier courier = couriers.iterator().next();
						if(courier!=null){
							System.out.println("自动分单成功");
							System.out.println("快递员姓名为:"+courier.getName());
							//保存订单
							savOrder(order, courier);
							//生成工单
							generateWorkBill(order);
							return;
						}
					}
				}
				
			}
			
		}
		
		//自动分单,根据关键辅助关键字查询分区-----定区----快递员 
		for(SubArea subArea: order.getSendArea().getSubareas()){
			//判断用户输入的发货地址是否包含分区的关键字
			if(order.getSendAddress().contains(subArea.getAssistKeyWords())){
				//如果包含,根据分区找到定区
				FixedArea fixedArea = subArea.getFixedArea();
				if(fixedArea!=null){
					Set<Courier> couriers = fixedArea.getCouriers();
					if(couriers!=null){
						Courier courier = couriers.iterator().next();
						if(courier!=null){
							System.out.println("自动分单成功");
							System.out.println("快递员姓名为:"+courier.getName());
							//保存订单
							savOrder(order, courier);
							//生成工单
							generateWorkBill(order);
							return;
						}
					}
				}
				
			}
			
		}
		
		//自动检索不成功进入自动分单
		order.setOrderType("2");
		System.out.println("进入手动分单模式");
		orderRepository.save(order);
	}


	//生成工单
	private void generateWorkBill(final Order order) {
		//创建工单对象,并为所有成员属性初始化
		WorkBill workBill = new WorkBill();
		
		workBill.setBuildtime(new Date());
		workBill.setCourier(order.getCourier());
		workBill.setOrder(order);
		workBill.setPickstate("新单");
		workBill.setType("新");
		workBill.setRemark(order.getRemark());
		String randomCode = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(randomCode);
		
		//调用远程服务,向用户发送信息
		final String msg = "短信序号：" + randomCode + ",取件地址：" + order.getSendAddress()
		+ ",联系人:" + order.getSendName() + ",手机:"
		+ order.getSendMobile() + "，留言："
		+ order.getSendMobileMsg();

		// 调用MQ服务，发送一条消息
		jmstemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone",order.getCourier().getTelephone());
				mapMessage.setString("msg", msg);
				return mapMessage;
			}
		});
		//发送信息完毕后,将工单状态修改为"已通知"
		workBill.setPickstate("已通知");
	}


	//保存订单的方法
	private void savOrder(Order order, Courier courier) {
		//设置分单类型(自动分单)
		order.setOrderType("1");
		//将快递员关联到订单中
		order.setCourier(courier);
		//调用dao层保存订单
		orderRepository.save(order);
	}


	@Override
	public Order findOrderByOrderNum(String orderNum) {
		return orderRepository.findOrderByOrderNum(orderNum);
	}

}
